package com.powernode.model;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * Security安全框架认识的安全用户对象
 *
 * @author ZhangYu
 * @date 2024/12/1 14:29
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SecurityUser implements UserDetails {

    //商城后台管理系统用户的相关属性

    /**
     * 用户id
     */
    private Long userId;

    /**
     * 用户名
     */
    private String username;

    /**
     * 密码
     */
    private String password;

    /**
     * 状态  0：禁用   1：正常
     */
    private Integer status;

    /**
     * 用户所在的商城Id
     */
    private Long shopId;

    /**
     * 登录类型
     */
    private String loginType;

    /**
     * 用户权限集合
     */
    private Set<String> userPerms = new HashSet<>();

    //

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.loginType + this.userId;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }

    public Set<String> getUserPerms() {
        HashSet<String> finalPermsSet = new HashSet<>();
        //循环遍历用户权限集合
        for (String userPerm : userPerms) {
            //判断是否包含'，'
            if (userPerm.contains(",")) {
                String[] realPerms = userPerm.split(StrUtil.COMMA);
                finalPermsSet.addAll(Arrays.asList(realPerms));
            } else {
                finalPermsSet.add(userPerm);
            }
        }
        return finalPermsSet;
    }

}
